<template>
  <div>
    <el-upload
      :class="{ disabled: total }"
      action="https://jsonplaceholder.typicode.com/posts/"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="onRemove"
      :file-list="fileList"
      :limit="limit"
      :on-change="onChange"
      :http-request="handleFileInUploading"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" title="图片预览" width="60%">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import cos from '@/utils/cos'
name: 'UploadImg'
export default {
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      imgs: undefined
    }
  },
  computed: {
    total () {
      return this.fileList.length >= this.limit
    }
  },
  methods: {
    handleFileInUploading ({ file }) {
      const currentImg = this.fileList.find(item => item.uid === file.uid)
      cos.uploadFile(
        {
          Bucket: 'hrsass27-1314436757' /* 填写自己的 bucket，必须字段 */,
          Region: 'ap-nanjing' /* 存储桶所在地域，必须字段 */,
          Key:
            +Date.now() +
            file.name /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */,
          Body: file, // 上传文件对象
          SliceSize: 1024 * 1024 * 5,
          onProgress: function (progressData) {
            console.log(JSON.stringify(progressData))
          }
        },
        function (err, data) {
          if (err) {
            console.log('上传失败', err)
          } else {
            console.log(data)
            console.log('上传成功')
            console.log(data.Location)
            currentImg.url = '//' + data.Location
          }
        }
      )
    },

    /**
     * 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
     */
    onChange (file, fileList) {
      this.fileList = [...fileList]
      console.log(file)
    },
    /**
     * 文件移除时钩子
     */
    onRemove (file, fileList) {
      this.fileList = [...fileList]
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled {
  ::v-deep {
    .el-upload--picture-card {
      display: none;
    }
  }
}
</style>
